package com.yupi.project.service.impl;

import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.baomidou.mybatisplus.core.conditions.update.UpdateWrapper;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.lc.lcapicomment.model.entity.UserInterfaceInfo;

import com.yupi.project.common.ErrorCode;
import com.yupi.project.exception.BusinessException;
import com.yupi.project.mapper.UserInterfaceInfoMapper;
import com.yupi.project.service.UserInterfaceInfoService;
import org.springframework.stereotype.Service;

import java.math.BigDecimal;
import java.util.Map;

/**
* @author 罗超
* @description 针对表【user_interface_info(用户接口调用表)】的数据库操作Service实现
* @createDate 2024-10-17 23:01:40
*/
@Service
public class UserInterfaceInfoServiceImpl extends ServiceImpl<UserInterfaceInfoMapper, UserInterfaceInfo>
    implements UserInterfaceInfoService {

    @Override
    public void validUserInterfaceInfo(UserInterfaceInfo userInterfaceInfo, boolean add) {
        if (userInterfaceInfo== null) {
            throw new BusinessException(ErrorCode.PARAMS_ERROR, "参数为空");
        }
        if(userInterfaceInfo.getTotalNum()<0){
            throw new BusinessException(ErrorCode.PARAMS_ERROR, "调用总次数不能小于0");
        }
        if(userInterfaceInfo.getLeftNum()<0 ||userInterfaceInfo.getTotalNum()<userInterfaceInfo.getLeftNum()){
            throw new BusinessException(ErrorCode.PARAMS_ERROR, "剩余调用次数不能小于总调用次数");
        }

    }

    @Override
    public boolean invokeCount(Long interfaceInfoId, Long userId) {
        if(interfaceInfoId<=0||userId<=0){
            throw new BusinessException(ErrorCode.PARAMS_ERROR, "用户信息或者接口信息错误");
        }
        //todo 需要考虑防止别人让一下请求非100次

        UpdateWrapper<UserInterfaceInfo> updateWrapper = new UpdateWrapper<>();
        updateWrapper.eq("interfaceInfoId", interfaceInfoId)
                .eq("userId", userId);
        updateWrapper.gt("leftNum", 0);
        updateWrapper.setSql("leftNum = leftNum - 1,totalNum = totalNum + 1");
        return this.update(updateWrapper);
    }

    @Override
    public boolean isHaveInvoke(Long interfaceInfoId, Long userId) {
        if(interfaceInfoId<=0||userId<=0){
            throw new BusinessException(ErrorCode.PARAMS_ERROR, "用户信息或者接口信息错误");
        }
        QueryWrapper<UserInterfaceInfo> queryWrapper=new QueryWrapper<>();
        queryWrapper.select("sum(leftNum) as leftNum")
                .eq("interfaceInfoId",interfaceInfoId)
                .eq("userId",userId);
        Map<String, Object> result = this.baseMapper.selectMaps(queryWrapper).stream().findFirst().orElse(null);


        if (result != null) {
            Object leftNumObj = result.get("leftNum");
            if (leftNumObj != null && ((BigDecimal) leftNumObj).compareTo(BigDecimal.ZERO) > 0) {
                return true;
            }
        }

        return false;
    }


}




